﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Text;


namespace Web.Views.WorkAssistant
{
    /// <summary>
    /// $codebehindclassname$ 的摘要说明
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    public class OrgUserHandle : IHttpHandler
    {
        string OrgTopName=  ConfigurationManager.AppSettings["OrgTopName"];
        string OrgTopID = ConfigurationManager.AppSettings["OrgTopID"];
        public void ProcessRequest(HttpContext context)
        {
            string json = "";
            string orgId = null;
            string oldUserId = null;
            string oldOrgID = null;
            //公司通讯录
            if (context.Request.QueryString["CompanyAdress"] != null)
            {
                string toporgid = null;
                if (context.Request["pid"] != null)
                {
                    orgId = context.Request["pid"];
                }
                if (context.Request.QueryString["toporgid"] != null)
                {
                    toporgid = context.Request.QueryString["toporgid"];
                }
                if (context.Request.QueryString["oldOrgId"] != null)
                {
                    oldOrgID = context.Request.QueryString["oldOrgId"];
                }
                if (context.Request.QueryString["oldUserId"] != null)
                {
                    oldUserId = context.Request.QueryString["oldUserId"];
                }

                bool showOrgCheckbox = true;
                if (context.Request.QueryString["ShowOrgCheckbox"] != null)
                {
                    showOrgCheckbox =Boolean.Parse( context.Request.QueryString["ShowOrgCheckbox"]);
                }
                
                json = GetCompanyUserData(orgId, oldOrgID, oldUserId,toporgid,showOrgCheckbox);
            }

            //公司组织机构
            if (context.Request.QueryString["CompanyOrg"] != null)
            {
                string parentId = string.Empty;
                string toporgid = null;
                if (context.Request.QueryString["parentId"] != null)
                {
                    parentId = context.Request.QueryString["parentId"];
                }
                if (context.Request.QueryString["toporgid"] != null)
                {
                    toporgid = context.Request.QueryString["toporgid"];
                }
                json = GetOrgJson(parentId,toporgid);
            }
            if (context.Request["AllOrgUser"] != null)
            {
                string topOrg = OrgTopID;
                if( context.Request["topOrg"]!=null)
                    topOrg = context.Request["topOrg"];
                //第一次加载
                //string topTreeData = GetCompanyUserData(null, null, null, topOrg);
                string allTreeData = GetCompanyAllOrgUser(topOrg);
               //json = "[{\"topTreeData\":" + topTreeData + ",\"allTreeData\":"+allTreeData+"}]";
               json = allTreeData;
            }
            context.Response.ContentType = "text/json";
            context.Response.Write(json);
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

        #region   公司通讯录（加载到2级）
        private string GetCompanyUserData(string orgId, string oldOrgId, string oldUserId,string toporgid,bool showOrgCheckbox)
        {
            bool bCheck = false;
            StringBuilder result = new StringBuilder("[");
            string jsonFormat = "{{\"id\": \"{0}\", \"text\": \"{1}\",\"pid\": \"{2}\",\"showCbx\": {7} ,\"iconCls\": \"{3}\",  \"checked\": {4}, \"state\": \"{5}\",\"attributes\":{{\"type\": \"{6}\"}}}},";
            string sqlFormat = string.Empty;
            if (string.IsNullOrEmpty(orgId))
            {
                sqlFormat = @"select a.org_ID id,a.parent_id pid, a.org_name text,case when a.unit_level!='Sys_UnitLevel--2' then 'org'
else 'cType' end type,a.Order_Num order_num ,'' as loginame from P_AUTH_ORG a inner join
P_AUTH_ORG b on a.Parent_ID=b.Org_ID
where (a.Parent_ID='{0}' or b.Parent_ID='{0}') and (b.status is null or b.Status<>'Org_Status--0') and ( a.status is null or a.status<>'Org_Status--0' ) 
union
select a.org_ID id,a.parent_id pid,a.org_name text,'cType' type,a.Order_Num as order_num ,'' as loginame from P_AUTH_ORG a
where  a.org_ID='{0}'   and (a.status is null or a.Status<>'Org_Status--0')
union
select a.user_Id id,a.Org_Id pid,a.user_name text,'user' type,a.Order_NUm order_num,'' as loginame from P_AUTH_User a inner join P_AUTH_ORG b on
a.ORG_ID=b.ORG_ID where (b.Parent_ID='{0}' or b.Org_ID='{0}') and (b.status is null or b.Status<>'Org_Status--0') and ( a.Status_ID is null or a.Status_ID<>'User_Status--0' )    order by order_num ";
                if (string.IsNullOrEmpty(toporgid))
                {
                    sqlFormat = string.Format(sqlFormat, OrgTopID);
                }
                else
                {
                    sqlFormat = string.Format(sqlFormat, toporgid);
                }
            }
            else
            {
                sqlFormat = @"select a.org_ID id,a.parent_id pid, a.org_name text,case when a.unit_level!='Sys_UnitLevel--2' then 'org'
else 'stype' end type,a.Order_Num order_num ,'' as loginame from P_AUTH_ORG a 
where a.parent_id='{0}' and (a.status is null or a.Status<>'Org_Status--0')
union
select a.user_Id id,a.Org_Id pid,a.user_name text,'user' type,a.Order_NUm order_num,'' as loginame from P_AUTH_User a inner join P_AUTH_ORG b on
a.ORG_ID=b.ORG_ID where b.Org_ID='{0}' and (b.status is null or b.Status<>'Org_Status--0') and ( a.Status_ID is null or a.Status_ID<>'User_Status--0' )   order by pid,type desc,order_num ";
                sqlFormat = string.Format(sqlFormat, orgId);
            }
            IMDataHelper dal = new IMDataHelper();
            DataTable dt = dal.DBHelper.ExecuteDataSet(sqlFormat).Tables[0];
            foreach (DataRow item in dt.Rows)
            {
                bCheck = false;
                if (item["type"].ToString() == "user")
                {
                    if (!string.IsNullOrEmpty(oldUserId))
                    {
                        string[] arrOldUserId = oldUserId.Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries);
                        bCheck = ((IList)arrOldUserId).Contains(item["id"].ToString());
                    }
                    result.Append(string.Format(jsonFormat, item["id"], item["text"], item["pid"], "icon-user", bCheck.ToString().ToLower(), "open", item["type"], showOrgCheckbox.ToString().ToLower()));
                }
                else if (item["type"].ToString() == "sType")
                {
                    result.Append(string.Format(jsonFormat, item["id"], item["text"], item["pid"], "icon-unit", bCheck.ToString().ToLower(), "open", item["type"], "false"));
                }
                else if (item["type"].ToString() == "cType")
                {
                    result.Append(string.Format(jsonFormat, item["id"], item["text"], item["pid"], "icon-unit", bCheck.ToString().ToLower(), "closed", item["type"], "false"));
                }
                else
                {
                    if (!string.IsNullOrEmpty(oldOrgId))
                    {
                        string[] arrOldUserId = oldUserId.Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries);
                        bCheck = ((IList)arrOldUserId).Contains(item["id"].ToString());
                    }
                    if (dt.Select("pid='" + item["id"] + "'").Length > 0)
                    {
                        //result.Append(string.Format(jsonFormat, item["id"], item["text"], item["pid"], "icon-org", bCheck.ToString().ToLower(), "open", item["type"], "true"));
                        result.Append(string.Format(jsonFormat, item["id"], item["text"], item["pid"], "icon-org", bCheck.ToString().ToLower(), "open", item["type"], showOrgCheckbox.ToString().ToLower()));
                    }
                    else
                    {
                        //result.Append(string.Format(jsonFormat, item["id"], item["text"], item["pid"], "icon-org", bCheck.ToString().ToLower(), "closed", item["type"], "true"));
                        result.Append(string.Format(jsonFormat, item["id"], item["text"], item["pid"], "icon-org", bCheck.ToString().ToLower(), "closed", item["type"], showOrgCheckbox.ToString().ToLower()));
                    }
                }
            }
            if (result.Length > 1)
            {
                result = result.Remove(result.Length - 1, 1);
            }
            result.Append("]");
            return result.ToString();
        }
        #endregion

        #region 公司组织机构
        private string GetOrgJson(string parentId, string toporgid)
        {

            bool bCheck = false;
            StringBuilder result = new StringBuilder("[");
            string jsonFormat = "{{\"id\": \"{0}\", \"text\": \"{1}\",\"pid\": \"{2}\",\"showCbx\": {7} ,\"iconCls\": \"{3}\",  \"checked\": {4}, \"state\": \"{5}\",\"attributes\":{{\"type\": \"{6}\"}}}},";
            string sqlFormat = string.Empty;
            if (string.IsNullOrEmpty(parentId))
            {
                sqlFormat = @"select a.org_ID id,a.parent_id pid, a.org_name text,case when a.unit_level!='Sys_UnitLevel--2' then 'org'
else 'cType' end type,a.Order_Num order_num,a.Org_RealLevel realLevel from P_AUTH_ORG a inner join
P_AUTH_ORG b on a.Parent_ID=b.Org_ID
where (a.Parent_ID='{0}' or b.Parent_ID='{0}') and a.Status='Org_Status--1'  and b.Status='Org_Status--1' 
union
select a.org_ID id,a.parent_id pid, a.org_name text,'cType' type,a.Order_Num order_num,a.Org_RealLevel realLevel from P_AUTH_ORG a
where a.org_ID='{0}' and a.Status='Org_Status--1'  order by realLevel,order_num";
                if (string.IsNullOrEmpty(toporgid))
                {
                    sqlFormat = string.Format(sqlFormat, OrgTopID);
                }
                else
                {
                    sqlFormat = string.Format(sqlFormat, toporgid);
                }
            }
            else
            {
                sqlFormat = @"select a.org_ID id,a.parent_id pid, a.org_name text,case when a.unit_level!='Sys_UnitLevel--2' then 'org'
else 'cType' end type,a.Order_Num order_num,a.Org_RealLevel realLevel  from P_AUTH_ORG a inner join
P_AUTH_ORG b on a.Parent_ID=b.Org_ID
where  (a.Parent_ID='{0}' or b.Parent_ID='{0}')  and a.Status='Org_Status--1'  and b.Status='Org_Status--1' order by realLevel,order_num";
                sqlFormat = string.Format(sqlFormat, parentId);
            }
            IMDataHelper dal = new IMDataHelper();
            DataTable dt = dal.DBHelper.ExecuteDataSet(sqlFormat).Tables[0];
            DataRow[] rows = null;
            if (!string.IsNullOrEmpty(toporgid))
            {
                rows = dt.Select("id='" + toporgid + "' or pid='" + toporgid + "'", "realLevel,order_num");
            }
            else
            {
                if (string.IsNullOrEmpty(parentId))
                {
                    rows = dt.Select("pid='0' or pid='175'", "realLevel,order_num");
                }
                else
                {
                    rows = dt.Select("pid='" + parentId + "'", "realLevel,order_num");
                }
            }
            string iconCss = string.Empty;
            foreach (DataRow item in rows)
            {
                iconCss = item["type"].ToString() == "cType" ? "icon-unit" : "icon-org";
                string openstatus = string.Empty;
                if (dt.Select("pid='" + item["id"] + "'").Length > 0)
                {
                    if (item["ID"].ToString() == OrgTopID || item["ID"].ToString()==toporgid)
                    {
                        openstatus = "open";
                    }
                    else
                    {
                        openstatus = "closed";
                    }
                    result.Append(string.Format(jsonFormat, item["id"], item["text"], item["pid"], iconCss, bCheck.ToString().ToLower(), openstatus, item["type"], "true"));
                }
                else
                {
                    openstatus = "open";
                    result.Append(string.Format(jsonFormat, item["id"], item["text"], item["pid"], iconCss, bCheck.ToString().ToLower(), openstatus, item["type"], "true"));
                }
            }
            if (result.Length > 1)
            {
                result = result.Remove(result.Length - 1, 1);
            }
            result.Append("]");
            return result.ToString();
        }
        #endregion

        #region 获取公司通讯录全部机构和人
        public string GetCompanyAllOrgUser(string org_ID)
        {
            string sql = @"select a.org_ID id,a.parent_id pid, a.org_name text,case when a.unit_level!='Sys_UnitLevel--2' then 'org'
else 'cType' end type,a.Order_Num order_num ,'' as loginame from P_AUTH_ORG a
where  ( a.Status is null or  a.Status<>'Org_Status--0')
union all
select a.user_Id id,a.Org_Id pid,a.user_name text,'user' type,a.Order_NUm order_num,cast(a.login_ID as varchar2(100)) as loginame from P_AUTH_User a inner join P_Auth_ORG b on
a.Org_ID=b.org_ID where ( a.Status_ID is null or a.Status_ID<>'User_Status--0' )
 order by order_num 
  ";
            IMDataHelper im = new IMDataHelper();
            List<TreeData> dataList = new List<TreeData>();
            DataSet ds = im.DBHelper.ExecuteDataSet(sql);
            string iconCss = string.Empty,state = string.Empty;
            bool showCbx = true;
            if(ds!=null && ds.Tables[0].Rows.Count>0)
            {
                foreach(DataRow row in ds.Tables[0].Rows)
                {
                    TreeData data = new TreeData();
                    data.id = row["id"].ToString();
                    data.pid = row["pid"].ToString();
                    data.text = row["text"].ToString();
                    data.attributes.parentId = row["pid"].ToString();
                    data.attributes.type = row["type"].ToString();
                    if (row["type"].ToString() == "cType")
                    {
                        iconCss = "icon-unit";
                        showCbx = false;
                        data.showCbx = showCbx;
                        data.iconCls = iconCss;
                    }
                    else if (row["type"].ToString() == "user")
                    {
                        iconCss = "icon-user";
                        showCbx = true;
                        state = "open";
                        data.state = state;
                        data.showCbx = showCbx;
                        data.iconCls = iconCss;
                    }
                    else
                    {
                        if (row["id"].ToString() == org_ID)
                        {
                            iconCss = "icon-unit";
                            showCbx = false;
                            state = "closed";
                            data.state = state;
                            data.showCbx = showCbx;
                            data.iconCls = iconCss;
                        }
                        else
                        {
                            iconCss = "icon-org";
                            showCbx = true;
                            state = "closed";
                            data.state = state;
                            data.showCbx = showCbx;
                            data.iconCls = iconCss;
                        }
                    }
                    if (row["pid"].ToString() == org_ID || row["id"].ToString() == org_ID)
                    {
                        state = "open";
                        iconCss = "icon-unit";
                        data.state = state;
                        data.showCbx = showCbx;
                        data.iconCls = iconCss;
                    }
                    //如果没有parentId为这个节点的，不显示+号
                    if (row["type"].ToString() != "user" && ds.Tables[0].Select("pid='" + row["id"] + "'").Length <= 0)
                    {
                        state = "open";
                        showCbx = false;
                        data.state = state;
                        data.showCbx = showCbx;
                        data.iconCls = iconCss;
                    }
                    dataList.Add(data);
                }
            }
            System.Web.Script.Serialization.JavaScriptSerializer jsonSerialisze = new System.Web.Script.Serialization.JavaScriptSerializer();
            jsonSerialisze.MaxJsonLength = 10240000;
            return jsonSerialisze.Serialize(dataList);
        }
        #endregion
    }

    public struct   TreeData
    {
        public string id;
        public string text;
        public string pid;
        public string iconCls;
        public bool showCbx;
        public string bChecked;
        public bool chkDisabled;
        public bool dbCheck;
        public string state;
        public TreeAttribute attributes;
    }
    
    public struct TreeAttribute
    {
        public string type;
        public string parentId;
    }
}
